package controllers;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import dao.common.BrandManager;
import dao.hibernate.BrandManagerHB;
import models.entities.PaginatedList;
import models.helpers.ImageHelper;
import models.json.GoogleImageResult;
import models.shop.*;
import play.Play;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.With;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

@With(Secure.class)
public class BrandAdmin extends Controller {
    private static BrandManager brandManager = new BrandManagerHB();

    @Check("admin")
    public static void list(int pageNumber) {
        int pageSize = 20;
        PaginatedList<Brand> brands = brandManager.listAll(pageNumber, pageSize);
        render("/Brand/list.html", brands, params);
    }

    @Check("admin")
    public static void display(int brandId, int start, String title) throws IOException {
        Brand brand = brandManager.getById(brandId);
        GoogleImageResult googleImageResult = getImages(title == null ? brand.title : title, start);
        render("/Brand/display.html", brand, googleImageResult);
    }


    private static GoogleImageResult getImages(String title, int start) throws IOException {
        String url = String.format("https://ajax.googleapis.com/ajax/services/search/images?start=%2$s&rsz=8&v=1.0&q=%1$s logo", title, start);
        WS.HttpResponse httpResponse = WS.url(url.replace(" ", "+")).get();
        JsonElement json = httpResponse.getJson();
        Gson gson = new Gson();
        GoogleImageResult googleImage = gson.fromJson(((JsonObject) json).get("responseData"), GoogleImageResult.class);
        return googleImage;
    }

    public static void saveImage(int brandId, String imageUrl) throws IOException {
        models.shop.Image image = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));
            image = ImageHelper.saveImage(bufferedImage, Play.getFile("data").toString(), "brands");
            models.shop.Image existentImage = brandManager.getExistentImage(brandId);
            brandManager.updateImage(brandId, image);
            ImageHelper.deleteImage(existentImage, Play.getFile("data").toString());
            display(brandId, 0, null);
        } catch (Exception ex) {
            if (image != null) {
                ImageHelper.deleteImage(image, Play.getFile("data").toString());
                brandManager.deleteImage(brandId, image.md5);
            }
            display(brandId, 0, null);
        }
    }
}
